<?php
namespace backend\models;
use backend\helpers\Pinyin;
use Yii;
use yii\helpers\ArrayHelper;
/**
 * User model
 *
 * @property integer $id
 * @property string $username
 * @property string $realname
 * @property string $password_hash
 * @property string $password_reset_token
 * @property string $email
 * @property string $auth_key
 * @property integer $role
 * @property integer $leader
 * @property integer $status
 * @property integer $created_at
 * @property integer $updated_at
 * @property integer $organization_id
 * @property string $password write-only password
 */
class User extends \common\models\User
{
    public $password;
    public $repassword;
    private $_statusLabel;
    private $_roleLabel;
    /**
     * @inheritdoc
     */
    public function getStatusLabel()
    {
        if ($this->_statusLabel === null) {
            $statuses = self::getArrayStatus();
            $this->_statusLabel = $statuses[$this->status];
        }
        return $this->_statusLabel;
    }
    /**
     * @inheritdoc
     */
    public static function getArrayStatus()
    {
        return [
            self::STATUS_ACTIVE => Yii::t('app', 'STATUS_ACTIVE'),
            self::STATUS_INACTIVE => Yii::t('app', 'STATUS_INACTIVE'),
            //self::STATUS_DELETED => Yii::t('app', 'STATUS_DELETED'),
        ];
    }
    public static function getArrayRole()
    {
        return ArrayHelper::map(Yii::$app->authManager->getRoles(), 'name', 'description');
    }


    public static function getRole(){
        return  Auth::find()->where(['type' => 1,"substring_index(name,'-',1)"=>Yii::$app->user->identity->organization_id])->all();
    }

    public function getUnassignedItems()
    {
        return ArrayHelper::map(Yii::$app->DbManager->getItems(null, $this->item !== null ? [$this->item->name] : []), 'name', function ($item) {
            return empty($item->description) ? $item->name : $item->name . ' (' . $item->description . ')';
        });
    }

    public function explodeRole($role){
        return is_array($role) ? $role : explode(',',$role);
    }

    public function getRoleName($role){
        if($role){
            $role_array = explode(',',$role);
            $role_array_new = array();
            foreach ($role_array as $item) {
                $role = Auth::find()->where(['name'=>$item])->one();
                if($role){
                    $role_array_new[] = $role->description;
                }

            }
            return implode(',',$role_array_new);

        }
        return null;
    }

    public function getRoleLabel()
    {
        if ($this->_roleLabel === null) {
            $roles = self::getArrayRole();
            $this->_roleLabel = $roles[$this->role];
        }
        return $this->_roleLabel;
    }

    /**
      * @inheritdoc
      */
    public function rules()
    {
        return [
            [['password','repassword', 'realname','mobile','role'], 'required'],
           // [['password', 'repassword'], 'required', 'on' => ['admin-create']],
            [['username', 'realname', 'password', 'mobile'], 'trim'],
            [['password', 'repassword'], 'string', 'min' => 6, 'max' => 16],
            [['status','mobile', 'department','leader', 'created_at', 'updated_at', 'created_by', 'updated_by','organization_id'], 'integer'],
            // Unique
            //[['username'], 'unique'],
            // Username
            ['username', 'string', 'min' => 4, 'max' => 12],
            ['username','match','pattern'=>'/^[a-zA-Z0-9_]+$/','message'=>'{attribute}只能由英文字母、数字、下划线组成'],

            ['realname', 'filter', 'filter' => 'trim'],
            ['realname', 'required'],
            ['realname', 'string', 'min' => 2, 'max' => 8],
            ['realname','match','pattern'=>'/^[\x{4e00}-\x{9fa5}]+$/u','message'=>'{attribute}必须为中文汉字'],


            ['email', 'email'],
            ['email', 'unique', 'targetClass' => '\common\models\User', 'message' => '该电子邮箱已经被占用.'],

            ['mobile', 'required'],
            ['mobile', 'integer'],
            ['mobile','match','pattern'=>'/^1[0-9]{10}$/','message'=>'{attribute}必须为1开头的11位纯数字'],
            ['mobile', 'string', 'min'=>11,'max' => 11],
            ['mobile', 'unique', 'targetClass' => '\common\models\User', 'message' => '该手机号码已经被占用.'],

            ['telphone', 'string', 'max' => 50],
            // Repassword
            ['repassword', 'compare', 'compareAttribute' => 'password'],
            //['status', 'default', 'value' => self::STATUS_ACTIVE],
            ['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_INACTIVE, self::STATUS_DELETED]],
            // Status
            //['role', 'in', 'range' => array_keys(self::getArrayRole())],
        ];
    }
    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        return [
            'admin-create' => ['username', 'realname','email','telphone', 'password','status', 'role','department','leader','position','mobile'],
            'admin-update' => ['realname','email','telphone', 'status', 'role','department','leader','position','mobile'],
            'admin-password' => ['password', 'repassword'],
        ];
    }
    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        $labels = parent::attributeLabels();
        return array_merge(
            $labels,
            [
                'password' => Yii::t('app', 'Password'),
                'repassword' => Yii::t('app', 'Repassword'),
                'mobile' => Yii::t('app', 'Mobile'),
                'qq' => Yii::t('app', 'Qq'),
                'url' => Yii::t('app', 'Url'),
                'address' => Yii::t('app', 'Address'),
                'telphone' => Yii::t('app', 'Department ').Yii::t('app', 'Telphone'),
                'department' => Yii::t('app', 'Department'),
                'position' => Yii::t('app', 'Position'),
                'leader' => Yii::t('app', 'Parent Leader'),

            ]
        );
    }
    /**
     * @inheritdoc
     */
    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            if ($this->isNewRecord) {
                $this->setPassword($this->password);
                $this->generateAuthKey();
                $this->generatePasswordResetToken();
                $this->created_by = Yii::$app->user->id;
                $this->updated_by = Yii::$app->user->id;
                $this->admin = 0;
                $this->username = Pinyin::getPinyin($this->realname);
                $this->organization_id = Yii::$app->user->identity->organization_id;
            }
            else if(!$this->isNewRecord && $this->password){
                $this->setPassword($this->password);
                $this->generateAuthKey();
                $this->generatePasswordResetToken();
                $this->updated_by = Yii::$app->user->id;
            }
            else{
                $this->updated_by = Yii::$app->user->id;
            }
            return true;
        }

        return false;
    }



    public static function get_user($user_id)
    {
        User::find()->select(['realname'])->where(['id'=>$user_id])->one()->realname;
    }

    public static function getUserame($user_id)
    {
        if($user_id){
            $user = User::find()->select(['username'])->where(['id'=>$user_id])->one();
            return isset($user) ? $user->username : Yii::t('app','Not Set');
        }
        else{
            return Yii::t('app','Not Set');
        }

    }

    public static function getRealname($id)
    {
        if($id){
            $user = User::find()->select(['realname'])->where(['id'=>$id])->one();
            return isset($user) ? $user->realname : Yii::t('app','Not Set');
        }
        else{
            return Yii::t('app','Not Set');
        }
    }

}
